package com.strongbj.iot.devices.guis.respnose.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessage;
import com.strongbj.iot.devices.dam.sub.dacai.message.DaCaiMessageType;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnEntity;
import com.strongbj.iot.devices.dam.sub.dacai.response.entity.ScreenReturnFactory;
import com.strongbj.iot.devices.guis.message.GUISOSMessageFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 打开网络参数页面的处理
 * 
 * @author yuzhantao
 *
 */
public class OpenNetParamsPageHandle implements IMessageHandle<DaCaiMessage, Object> {
	private static Logger logger = LogManager.getLogger(OpenNetParamsPageHandle.class.getName());
	protected final static String COMMAND_CODE = "B111"; // 打开页面命令的编号
//	protected final static String NET_PAGE_INDEX = "0004";  	// 网络设置页面的索引
	protected final static String DEFAULT_DEVICE_CODE = "000000"; // 设备默认编号
	protected final static byte[] EMPTY_DATAS = {}; // 空参数
	protected final static byte GET_NET_COMMAND = (byte) 0x22;
	private GUISOSMessageFactory gUISOSMessageFactory = new GUISOSMessageFactory();

	@Override
	public boolean isHandle(DaCaiMessage t) {
		if (t.getMessageType() == DaCaiMessageType.System && t.getCommand().equals(COMMAND_CODE)) {
			ScreenReturnEntity sr = ScreenReturnFactory.create(t.getDatas());

			// 如果控件类型为按钮，屏幕id为0，按钮id为4，就认为是打开网络界面
			if (sr.getControlType() == 16 && sr.getScreenId() == 0 && sr.getControlId() == 4)
				return true;
		}
		return false;
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DaCaiMessage t) {
		logger.info("打开网络参数页面的处理界面 open net screen");
		Channel channel = ctx.channel();

		ITaskManager taskManager = DAMManager.getTaskManager(t.getDamCode());
		// 发送获取网络参数的命令
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				if (channel != null && channel.isActive()) {
					OpenNetParamsPageHandle.this.sendGetLocalNetParamsMessage(channel,
							ByteUtil.hexStringToBytes(t.getDamCode()));
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					logger.error("主机没有找到指定channel");
				}
			}
		});

		return null;
	}

	/**
	 * 发送获取本地网络的消息
	 * 
	 * @param channel
	 */
	private void sendGetLocalNetParamsMessage(Channel channel, byte[] devCode) {
		final byte[] datas = getNetCommand(devCode);
		ByteBuf bs = Unpooled.copiedBuffer(datas);
		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {

			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("RU2000自动下发获取本地网络参数命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("RU2000自动下发获取本地网络参数命令失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	/**
	 * 获取下发给RU2000的获取网络参数命令
	 * 
	 * @param setTheMainframeTheIncome
	 */
	private byte[] getNetCommand(byte[] devCode) {
		byte[] data = new byte[0]; // 接受主机编号的临时byte数组
		return gUISOSMessageFactory.createGUISOSMessage(devCode, GET_NET_COMMAND, data);
	}
}
